import { Injectable } from '@nestjs/common';
import { CreateSystemDto } from './dto/create-system.dto';
import { UpdateSystemDto } from './dto/update-system.dto';
import { SysUserService } from '../sys-user/sys-user.service';
import { SysUser } from '../sys-user/entities/sys-user.entity';
import { omit, pick } from 'lodash';
import { UpdateUserDto } from './dto/update-user.dto';
import { UpdatePasswordDto } from './dto/update-password.dto';
import * as bcrypt from 'bcrypt';
import { CommonException } from '../../core/exception/common.exception';
@Injectable()
export class SystemService {
  constructor(private readonly sysUserService: SysUserService) {}

  async getProfile(user: { userId: any }): Promise<any> {
    return await this.sysUserService.getCurrentUser(user.userId);
  }

  // 更新下数据信息
  async updateProfile(user: { userId: number }, updateUserDto: UpdateUserDto) {
    return await this.sysUserService.updateCurrentUser(user.userId, {
      ...pick(updateUserDto, [
        'user_id',
        'nickName',
        'email',
        'sex',
        'phonenumber',
      ]),
    });
  }

  // 更新密码
  async updatePassword(user: any, updatePasswordDto: UpdatePasswordDto) {
    const queryUser = await this.sysUserService.getCurrentUser(user.userId);
    const password = queryUser.password;
    if (!bcrypt.compareSync(updatePasswordDto.oldPassword, password)) {
      throw new CommonException(500, '修改密码失败，旧密码错误');
    }
    if (bcrypt.compareSync(updatePasswordDto.newPassword, password)) {
      throw new CommonException(500, '新密码不能与旧密码相同');
    }
    // 更新下用户密码
    return await this.sysUserService.updateCurrentUser(user.userId, {
      password: bcrypt.hashSync(
        updatePasswordDto.newPassword,
        bcrypt.genSaltSync(10),
      ),
    });
  }

  create(createSystemDto: CreateSystemDto) {
    return 'This action adds a new system';
  }

  findAll() {
    return `This action returns all system`;
  }

  findOne(id: number) {
    return `This action returns a #${id} system`;
  }

  update(id: number, updateSystemDto: UpdateSystemDto) {
    return `This action updates a #${id} system`;
  }

  remove(id: number) {
    return `This action removes a #${id} system`;
  }
}
